package com.tg.app.activity.device.add;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.wifi.ScanResult;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;

import com.base.BaseActivity;
import com.tange.feature.data.structure.DeviceTypeBean;
import com.tange.module.core.wifi.scan.ApScanConfiguration;
import com.tg.app.R;
import com.tg.appcommon.android.DeviceAddSoundConstants;
import com.tg.appcommon.android.DialogUtil;
import com.tg.appcommon.android.SoundPlayerManager;
import com.tg.appcommon.android.TGLog;
import com.tg.appcommon.android.TGWifiUtil;
import com.tg.data.helper.DeviceTypeHelper;
import com.tange.core.backend.service.http.ClientObserver;
import com.tange.core.backend.service.api.CoreBackendService;
import com.tg.network.socket.http.TGHttp;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class ApSetWifiActivity extends BaseActivity implements View.OnClickListener {
    public static final String TAG = "ApSetWifiActivity";
    private EditText edtPassword;
    private EditText edtName;
    private ListView listView;
    private String mUUID;
    private final ArrayList<ScanResult> wifiApList = new ArrayList<>();
    private final ArrayList<String> stringArrayList = new ArrayList<>();
    public static final String EXT_UUID = "ApSetWifiActivity_uuid";
    public static final String EXT_HOTSPOT_PWD = "ApSetWifiActivity_hotspot_pwd";
    public static final String EXT_HOTSPOT_CAPABILITIES = "ApSetWifiActivity_hotspot_capabilities";
    public static final String EXT_WIFI = "ApSetWifiActivity_wifi";
    public static final String EXT_PWD = "ApSetWifiActivity_pwd";
    public static final String EXT_BATTERY_DEVICE = "ApSetWifiActivity_battery_device";
    public static final String EXT_DEVICE_TYPE = "ApSetWifiActivity_EXT_DEVICE_TYPE";
    private Button button;
    private ScanResult wifiAp;
    private String mDeviceWifi;
    private String mDevicePassword;
    private String mDeviceCapabilities;
    private String deviceType;

    private boolean playSound = true;

    private SoundPlayerManager soundPlayerManager;

    private final Handler uiHandler = new Handler(Looper.getMainLooper());

    private boolean isBatteryDevice = false;
    @Override
    public boolean shouldSetStatusBarColor() {
        return true;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//remove title bar  即隐藏标题栏
        setContentView(R.layout.fragment_ap_set_wifi);
        initView();
        hideActionBar();

        deviceType = getIntent().getStringExtra(EXT_DEVICE_TYPE);
        if (!TextUtils.isEmpty(deviceType)) {
            isBatteryDevice = DeviceTypeHelper.isBatteryDevice(deviceType);
        }

        TGLog.i(TAG, "onCreate: deviceType = " + deviceType);
        TGLog.i(TAG, "onCreate: isBatteryDevice = " + isBatteryDevice);

        if (DeviceTypeHelper.isLockBell(deviceType)) {
            playSound = false;
        }

        ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
                android.R.layout.simple_list_item_1
                , stringArrayList);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener((adapterView, view, i, l) -> {
            wifiAp = wifiApList.get(i);
            edtName.setText(wifiAp.SSID);
            listView.setVisibility(View.GONE);

        });
        getWifiList();
        stringArrayList.clear();
        for (ScanResult result : wifiApList) {
            stringArrayList.add(result.SSID);
        }

        mDeviceWifi = getIntent().getStringExtra(ApSetWifiActivity.EXT_UUID);
        mDevicePassword = getIntent().getStringExtra(ApSetWifiActivity.EXT_HOTSPOT_PWD);
        mDeviceCapabilities = getIntent().getStringExtra(ApSetWifiActivity.EXT_HOTSPOT_CAPABILITIES);
        getDeviceType(mDeviceWifi);

        TGLog.i(TAG, "onCreate: mDeviceWifi = " + mDeviceWifi);
        TGLog.i(TAG, "onCreate: mDevicePassword = " + mDevicePassword);
        TGLog.i(TAG, "onCreate: mDeviceCapabilities = " + mDeviceCapabilities);

        boolean isLocationGranted = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
        if (!isLocationGranted) {
            LocationGrantGuideActivity.launch(this);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        playSound();
    }

    private void playSound() {
        if (!playSound) return;
        if (soundPlayerManager != null) {
            soundPlayerManager.destroy();
        }
        soundPlayerManager = SoundPlayerManager.create(this);
        uiHandler.postDelayed(() -> {
            if (soundPlayerManager != null) {
                soundPlayerManager.download(DeviceAddSoundConstants.WifiChoose(ApSetWifiActivity.this), true);
            }
        }, 1000);
    }

    @Override
    protected void onPause() {
        super.onPause();
        pauseSound();
    }

    private void pauseSound() {
        if (!playSound) return;
        uiHandler.removeCallbacksAndMessages(null);
        if (soundPlayerManager != null) {
            soundPlayerManager.destroy();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == LocationGrantGuideActivity.REQUEST_CODE) {
            if (resultCode == RESULT_CANCELED) {
                finish();
            } else if (resultCode == RESULT_OK) {
                // 刷新WIFI列表
                refreshWifi();
            }
        } else if (requestCode == WiFiAccessGuideActivity.REQUEST_CODE) {
            if (resultCode == RESULT_CANCELED) {
                // do nothing
            } else if (resultCode == RESULT_OK) {
                goToConnectActivity();
            } else {
                finish();
            }
        }
    }

    private void refreshWifi() {
        getWifiList();
        stringArrayList.clear();
        for (ScanResult result : wifiApList) {
            stringArrayList.add(result.SSID);
        }
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
                android.R.layout.simple_list_item_1
                , stringArrayList);
        Log.i(TAG, "onActivityResult: wifilist - " + stringArrayList);
        listView.setAdapter(adapter);
    }

    private void getDeviceType(String wifi){
        if (TextUtils.isEmpty(wifi))return;
        mUUID = wifi.replaceAll(ApScanConfiguration.INSTANCE.apNamePrefixEndsWithUnderLine(),"");
        HashMap<String, String> map = new HashMap<>();
        map.put("uuid", mUUID);
        TGLog.i(TAG, "getDeviceType map =  " + map);
        TGHttp.getInstance().getDeviceType(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ClientObserver<DeviceTypeBean>() {
                    @Override
                    protected void onSuccess(final DeviceTypeBean content) {
                        if (content!=null){
                            deviceType =  content.getDevice_type();
                            TGLog.i(TAG, "getDeviceType onSuccess deviceType = " + deviceType);
                            isBatteryDevice = DeviceTypeHelper.isBatteryDevice(content.getDevice_type());
                        }

                    }

                    @Override
                    protected void onResponseError(int errorCode, String errorInfo) {
                        TGLog.i(TAG, "getDeviceType onResponseError errorCode = " + errorCode);
                    }

                    @Override
                    protected void onOtherError(String error) {

                    }
                });
    }
    private void getWifiList(){
        List<ScanResult> scanResults = TGWifiUtil.noSameName(TGWifiUtil.getWifiScanResult(this));
        wifiApList.clear();
        for (ScanResult result : scanResults){
            TGLog.i(TAG, "[getWifiList] result.SSID = " + result.SSID);
            if (!result.SSID.startsWith(ApScanConfiguration.INSTANCE.apNamePrefix())&&!wifiApList.contains(result)){
                wifiApList.add(result);
            }
        }
        Collections.sort(wifiApList, (o1, o2) -> o1.SSID.compareTo(o2.SSID));

    }

    @Override
    protected void initView() {
        edtName = findViewById(R.id.device_ap_add_set_wifi_name);
        edtPassword = findViewById(R.id.device_ap_add_set_wifi_password);
        listView = findViewById(R.id.device_ap_add_set_wifi_list);
        button = findViewById(R.id.btn_before_add_next);
        button.setOnClickListener(this);
        findViewById(R.id.btn_device_ap_add_more).setOnClickListener(this);
        CheckBox box = findViewById(R.id.device_ap_add_checkbox);
        box.setOnCheckedChangeListener((compoundButton, b) -> {
            if (b) {
                edtPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            } else {
                edtPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
            }
            String str = edtPassword.getText().toString();
            if (!TextUtils.isEmpty(str)) {
                edtPassword.setSelection(str.length());
            }
        });


        edtPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                updateBtnStatus();

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        edtName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (wifiAp != null && !TextUtils.equals(wifiAp.SSID, s)) {
                    wifiAp = null;
                }
                if (!TextUtils.isEmpty(s)) {
                    edtName.setSelection(s.length());
                }
                updateBtnStatus();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        button.setAlpha(0.4f);
        button.setEnabled(false);
        box.setChecked(true);

        findViewById(R.id.back_toolbar).setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.back_toolbar) {
            onBack();
        } else if (id == R.id.btn_before_add_next) {
            TGLog.d("btn_before_add_next click");
            String name = edtName.getText().toString().trim();
            if (TGWifiUtil.is5GHz(name)) {
                DialogUtil.openDlalog(this,
                        R.string.text_5g_wifi_title,
                        R.string.text_5g_wifi_content,
                        R.string.text_5g_wifi_next,
                        R.string.text_5g_wifi_cancel,
                        v -> {
                            TGLog.d("v id =" + v.getId());
                            goToWiFiConnectGuide();
                        },
                        v -> TGLog.d("v id =" + v.getId()));
            } else {
                goToWiFiConnectGuide();
            }
        } else if (id == R.id.btn_device_ap_add_more) {
            if (listView.getVisibility() == View.GONE) {
                listView.setVisibility(View.VISIBLE);
                InputMethodManager manager = ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE));
                if (manager != null)
                    manager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            } else {
                listView.setVisibility(View.GONE);
            }
        }
    }

    private void updateBtnStatus() {
        String name = edtName.getText().toString();
        if (TextUtils.isEmpty(name)) {
            button.setAlpha(0.4f);
            button.setEnabled(false);
            return;
        }
        if (wifiAp != null) {
            String pwd = edtPassword.getText().toString();
            boolean isEnctype = false;
            if (wifiAp.capabilities.contains("WEP") || wifiAp.capabilities.contains("PSK") || wifiAp.capabilities.contains("EAP")) {
                isEnctype = true;
            }
            if (isEnctype) {
                if (TextUtils.isEmpty(pwd) || pwd.length() < 8) {
                    button.setAlpha(0.4f);
                    button.setEnabled(false);
                    return;
                }
            }
        }

        button.setAlpha(1.0f);
        button.setEnabled(true);
    }



    @Override
    public void onBackPressed() {
        super.onBackPressed();
        onBack();
    }

    private void onBack() {
        setResult(0);
        finish();
    }

    private void goToWiFiConnectGuide() {
        WiFiAccessGuideActivity.launch(this, mDeviceWifi, mUUID);
    }

    private void goToConnectActivity() {
        TGLog.i(TAG, "[goToConnectActivity] ");
        Intent intent = new Intent(getBaseContext(), ApConnectActivity.class);
        intent.putExtra(ApSetWifiActivity.EXT_UUID, mDeviceWifi);
        intent.putExtra(ApSetWifiActivity.EXT_HOTSPOT_PWD, mDevicePassword);
        intent.putExtra(ApSetWifiActivity.EXT_HOTSPOT_CAPABILITIES, mDeviceCapabilities);
        intent.putExtra(ApSetWifiActivity.EXT_WIFI, edtName.getText().toString().trim());
        intent.putExtra(ApSetWifiActivity.EXT_PWD, edtPassword.getText().toString());
        intent.putExtra(ApSetWifiActivity.EXT_DEVICE_TYPE, deviceType);
        intent.putExtra(EXT_BATTERY_DEVICE,isBatteryDevice);
        startActivity(intent);
        finish();
    }
}
